package server;

import gms.ILookupTable;

import java.io.ByteArrayOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;

import server.CommandFactories.CmdType;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import network.MessageService;

import command.GetUserTimelineCommandFactory;
import command.ICommand;
import command.IResponse;
import command.protobuf.GetUserTimelineCmdArgsProtoBuf.*;
import command.protobuf.GetUserTimelineResponseProtoBuf.GetUserTimelineRes;
import command.protobuf.MessageBufProtoBuf.RpcMessage;
import config.Catalog;

public class ServerGetUserTimelineCommand implements ICommand {
	public static final CmdType cmdType = CmdType.getusertimeline;

	RpcMessage originMessage = null;
	private Socket socket;

	@Override
	public RpcMessage invoke() {
		try {
			GetUserTimelineCmdArgs args = GetUserTimelineCmdArgs
					.parseFrom(originMessage.getContent().toByteArray());

			GetUserTimelineRes.Builder resBuilder = GetUserTimelineRes
					.newBuilder();
			GetUserTimelineRes res = resBuilder.addTweet("uid:" + 
					args.getUid() + " start:" + args.getStart()).build();
			IResponse response = CommandFactories.getCommand(cmdType)
					.createResponse();
			response.set(res);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			/**
			 * send to all other nodes
			 */
			
			
			response.write(output);
			ByteString bString = ByteString.copyFrom(output.toByteArray());
			int flag = MessageService.RESPONSE_FLAG
					| (originMessage.getHeader().getFlag() & MessageService.CLIENT_SERVER_COMM);

			RpcMessage.Header header = RpcMessage.Header.newBuilder().setID(originMessage.getHeader().getID())
					.setCmdType(cmdType.ordinal()).setFlag(flag).build();
			RpcMessage message = RpcMessage.newBuilder().setContent(bString)
					.setHeader(header).build();
			
			return message;
		} catch (InvalidProtocolBufferException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public CmdType getCommandType() {
		return cmdType;
	}

	@Override
	public void setOrigin(RpcMessage origin, Socket socket) {
		this.originMessage = origin;
		this.socket = socket;
	}
}
